package ps.yj.y1j0.business.KVData;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import ps.yj.y1j0.data.YJDataObject;

import javax.ws.rs.FormParam;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: yanjun
 * Date: 13-1-12
 * Time: 下午11:45
 * To change this template use File | Settings | File Templates.
 */
public class YJKVDataObject extends YJDataObject {
    /**
     * 数据种类
     */
    @FormParam("dataKind")
    private String dataKind;

    /**
     * 数据项
     */
    @FormParam("dataValue")
    private String dataValue;

    public String getDataKind() {
        return dataKind;
    }

    public void setDataKind(String dataKind) {
        this.dataKind = dataKind;
    }

    public String getDataValue() {
        return dataValue;
    }

    public void setDataValue(String dataValue) {
        this.dataValue = dataValue;
    }

    @Override
    public String get(String property) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode nodes = mapper.readValue(dataValue, JsonNode.class);
            return nodes.get(property).asText();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String[] properties() {
        ObjectMapper mapper = new ObjectMapper();
        String[] properties = null;
        try {
            JsonNode nodes = mapper.readValue(dataValue, JsonNode.class);
            properties = new String[nodes.size()];
            int i = 0;
            Iterator<String> fields = nodes.getFieldNames();
            while (fields.hasNext()) {
                properties[i++] = fields.next();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return properties;
        }
    }

    public static void main(String args[]) {
        YJKVDataObject data = new YJKVDataObject();
        String json = "{\"address\": 111,\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"}";
        data.setDataValue(json);
        String[] properties = data.properties();
        for (String property : properties) {
            System.out.println(String.format("%s = %s", property, data.get(property)));
        }
    }
}
